import psutil
import serial

# for p in psutil.process_iter():
#     try:
#         print(p.pid)
#         print(p.name())
#         print(p.status())
#         print(p.username())
#         print(p.cpu_percent())
#         print('-' * 10)
#     except:
#         print('-' * 10)
from serial.tools.list_ports_linux import comports

start_alarm = "A0 01 01 A2"
stop_alarm = "A0 01 00 A1"


def alarm(send_data, com_str, bit):
    try:
        ser = serial.Serial(com_str, bit)  # 选择串口，并设置波特率
        if ser.is_open:
            ser.write(bytes.fromhex(send_data))  # 发送命令
            # ser.close()
        else:
            print("port open failed")
    except:
        print(f"{com_str} alarm failed!")


plist = list(comports())
for port in plist:
    msg = list(port)
    if len(msg[2].split("LOCATION=")) >= 2:
        if msg[2].split("LOCATION=")[1] == '1-7':
            _com1_str = msg[0]
            print("serial1:" + _com1_str)
        if msg[2].split("LOCATION=")[1] == '1-14.1':
            _com2_str = msg[0]
            print("serial2:" + _com2_str)
# 报警灯声光报警
alarm("/dev/ttyUSB0", start_alarm, 9600)
